/*
* @Date: 2021/3/6
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import React from 'react';
import ajax from 'decorate/ajax';
import './index.scss';
import CentralBank from 'business/CentralBank';
import Pulldown from 'components/Pulldown';
import Icon from 'components/Icon';
import Swiper from 'components/Swiper';

@ajax(CentralBank.url, CentralBank.meta, CentralBank.resolve)
export default class extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      page: 1,
      last_page: 1,
      onAjaxing: false,
    };
  }

  onNewsDetail = (e) => {
    const { newsId } = e.currentTarget.dataset;
    this.props.history.push(`/news/${newsId}`);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    const { data = [], page = 0 } = this.state;
    let article = [];
    if (page === 1) {
      article = nextProps.data;
    } else {
      article = data.concat(nextProps.data);
    }
    this.setState({
      data: article,
      last_page: nextProps.last_page,
      onAjaxing: false,
    });
  }

  onMore = (e) => {
    const { onAjaxing = true, page = 1, last_page = 1 } = this.state;
    if (e.currentTarget.scrollHeight - e.currentTarget.scrollTop - e.currentTarget.offsetHeight < 40 && !onAjaxing && page < last_page) {
      console.log('more')
      this.setState({
        page: page + 1,
        onAjaxing: true
      }, () => {
        this.postAjax()
          .then(res => {
            this.setState({
              onAjaxing: false
            });
          });
      });

    }
  }

  onPulldown  = () => {
    return this.postAjax();
  }

  render() {
    const { data = [] } = this.props;
    const { show = false } = this.props;
    if (data.length === 0 && show) {
      return (
        <Pulldown
          onLoading={this.onPulldown}
        >
          <div className="app-no-data">
            <Icon type="kong"/>
            <div className="no-data">暂无数据</div>
          </div>
        </Pulldown>
      )
    }
    return (
      <Swiper className="app-news-wrapper" style={{ display: show ? 'flex' : 'none' }}>
        {
          data.map((item) => {
            return (
              <div className="view-point-item-wrapper">
                <div className="view-point-item">
                  <div className="view-point-header">
                    <div className="view-point-title">{item.title}</div>
                    <div className="view-point-time">{item.time}</div>
                  </div>
                  <div className="view-point-info">
                    {item.info}
                  </div>
                </div>
              </div>
            );
          })
        }
      </Swiper>
    );
  }
}
